package Servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import DBFunction.*;
import DTO.*;
import Parser.StringtoMD5;
import Storage.GroupUserList;

/**
 * Servlet implementation class SeverAdminLogin
 */
public class ServerAdminLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger logger = Logger.getLogger(ServerAdminLogin.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServerAdminLogin() {
        super();

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String passwords = request.getParameter("passwords");
		Admin resultAdmin = new Admin();
		logger.info("ServerAdminLogin :Request user: "+username+" passwords :"+passwords);
		try {
			resultAdmin = AdminManager.getAdminByAccount(username);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String Error="Error";
		if( resultAdmin == null | !username.equals(resultAdmin.getAccount()) | username.isEmpty() ){
			Error="Wrong Username, please check again";
			request.getSession().setAttribute("error",Error);
			response.sendRedirect("index.jsp");
			logger.info("ServerAdminLogin :Username not found");
			logger.info("ServerAdminLogin :Login failed");
		}
		else if ( passwords.equals(resultAdmin.getPasswords() )) {
		request.getSession().removeAttribute("error");
		request.getSession().setAttribute("adminFirstName", resultAdmin.getFirstName());
		request.getSession().setAttribute("adminLastName", resultAdmin.getLastName());
		logger.info("ServerAdminLogin :Login Successfully");
		//response.sendRedirect("managementpage.jsp");
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ServerDisplay");
		   dispatcher.forward( request, response );
		}
		else {
			Error="Wrong Passwords, please check again";
			request.getSession().setAttribute("error",Error);
			response.sendRedirect("index.jsp");
			logger.info("ServerAdminLogin :Wrong Passwords");
			logger.info("ServerAdminLogin :Login failed");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
	}

}
